package com.clearliang.alarmnotice.service;

import android.app.AlarmManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.clearliang.alarmnotice.bean.AlarmBean;
import com.clearliang.alarmnotice.utils.VibratorUtil;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.clearliang.alarmnotice.view.GlobleConst.SP_ALARM;
import static com.clearliang.alarmnotice.view.GlobleConst.SP_ALARM_DETAILS;

/**
 * Created by ClearLiang on 2019/3/1
 * <p>
 * Function :
 */
public class StartAlarmService extends Service {
    private List<AlarmBean> alarmList;
    private Context context;
    private boolean isCanStart = false;     //是否可以开启任务时钟
    private int playNum = 3;                //重复播放次数
    private String playText = "";           //当前播放的文字内容
    private CountDownTimer mTimer,mTimer1;
    private Handler myHandler;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            LogUtils.e("任务更新");
            for (int i = 0; i < alarmList.size(); i++) {
                if (alarmList.get(i).isIsOpen()) {
                    startAlarms(alarmList.get(i));
                }
            }
        }
    };

    //创建服务时调用
    @Override
    public void onCreate() {
        super.onCreate();
        //LogUtils.e("onCreate");
        context = this;
        initData();
    }

    private void initData() {
        alarmList = new ArrayList<>();
        String alarmDetails = SPUtils.getInstance(SP_ALARM).getString(SP_ALARM_DETAILS, "");

        if (TextUtils.isEmpty(alarmDetails)) {
            isCanStart = false;
        } else {
            alarmList.addAll(JSON.parseArray(alarmDetails, AlarmBean.class));
            isCanStart = true;
        }
    }

    //执行服务的操作
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //LogUtils.e("onStartCommand");
        if (isCanStart) {
            for (int i = 0; i < alarmList.size(); i++) {
                // 该任务是否开启（checkBox为true时）
                if (alarmList.get(i).isIsOpen()) {
                    //LogUtils.e("启动内容", JSON.toJSONString(alarmList.get(i)));
                    startAlarms(alarmList.get(i));
                }
            }
            // 一天更新一次任务
            myHandler = new Handler();
            myHandler.postDelayed(runnable, AlarmManager.INTERVAL_DAY);// AlarmManager.INTERVAL_DAY
        } else {
            LogUtils.e("未检测到任务");
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void startAlarms(final AlarmBean alarmBean) {
        String startTime = alarmBean.getStartTime();
        String endTime = alarmBean.getEndTime();
        List<String> week = alarmBean.getWeekday();
        long triggerAtMillisStart = getTime(startTime);
        long triggerAtMillisEnd = getTime(endTime);

        //LogUtils.e("星期：", JSON.toJSONString(week), triggerAtMillisStart, triggerAtMillisEnd);
        for (String aWeek : week) {
            // 判断今天是否有任务
            if (aWeek.equals(TimeUtils.getChineseWeek(TimeUtils.getNowString()))) {
                LogUtils.e("任务开启——" + alarmBean.getName());
                // 判断今日的任务有没有过期
                if (triggerAtMillisStart > 0) {
                    mTimer = new CountDownTimer((triggerAtMillisStart), 1000) {

                        @Override
                        public void onTick(long millisUntilFinished) {
                                    /*if (!TestActivity.this.isFinishing()) {
                                        int remainTime = (int) (millisUntilFinished / 1000L);
                                        //LogUtils.e("======remainTime=====" + remainTime);
                                    }*/
                        }

                        @Override
                        public void onFinish() {
                            speekText(alarmBean.getContent());
                            LogUtils.e("======" + alarmBean.getName() + " 上课了=====");
                        }
                    };
                    mTimer.start();
                    mTimer1 = new CountDownTimer((triggerAtMillisEnd), 1000) {

                        @Override
                        public void onTick(long millisUntilFinished) {
                                    /*if (!TestActivity.this.isFinishing()) {
                                        int remainTime = (int) (millisUntilFinished / 1000L);
                                        //LogUtils.e("======remainTime=====" + remainTime);
                                    }*/
                        }

                        @Override
                        public void onFinish() {
                            speekText("当前任务已经完成");
                            LogUtils.e("======" + alarmBean.getName() + " 下课了=====");
                        }
                    };
                    mTimer1.start();
                } else if (triggerAtMillisEnd > 0) {
                    mTimer1 = new CountDownTimer((triggerAtMillisEnd), 1000) {

                        @Override
                        public void onTick(long millisUntilFinished) {
                                    /*if (!TestActivity.this.isFinishing()) {
                                        int remainTime = (int) (millisUntilFinished / 1000L);
                                        //LogUtils.e("======remainTime=====" + remainTime);
                                    }*/
                        }

                        @Override
                        public void onFinish() {
                            speekText("当前任务已经完成");
                            LogUtils.e("======" + alarmBean.getName() + " 下课了=====");
                        }
                    };
                    mTimer1.start();
                } else {
                    LogUtils.e(alarmBean.getName() + " - 该时间任务已经过时");
                }
            }
        }

    }

    //获取给定时间与当前时间的时间差（毫秒）
    // 15:45   18:52   12:12
    private long getTime(String startTime) {
        long time;
        DateFormat mFormat = new SimpleDateFormat("HH:mm", Locale.CHINA);
        time = TimeUtils.getTimeSpanByNow(startTime, mFormat, TimeConstants.MSEC);
        return time;
    }

    //销毁服务时调用
    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.e("onDestroy");
        if(mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
        if(mTimer1 != null){
            mTimer1.cancel();
            mTimer1 = null;
        }
        if(myHandler != null){
            myHandler.removeCallbacks(runnable);
        }

    }

    private void speekText(String msg) {
        playText = msg;
        LogUtils.e(playText);
        //1. 创建 SpeechSynthesizer 对象 , 第二个参数： 本地合成时传 InitListener
        SpeechSynthesizer mTts = SpeechSynthesizer.createSynthesizer(this, null);
        //2.合成参数设置，详见《 MSC Reference Manual》 SpeechSynthesizer 类
        //设置发音人（更多在线发音人，用户可参见 附录 13.2
        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan"); // 设置发音人 xiaoyan  vinn
        mTts.setParameter(SpeechConstant.SPEED, "30");// 设置语速
        mTts.setParameter(SpeechConstant.VOLUME, "80");// 设置音量，范围 0~100
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
        //设置合成音频保存位置（可自定义保存位置），保存在 “./sdcard/iflytek.pcm”
        //保存在 SD 卡需要在 AndroidManifest.xml 添加写 SD 卡权限
        //仅支持保存为 pcm 和 wav 格式， 如果不需要保存合成音频，注释该行代码
        //mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
        //3.开始合成
        mTts.startSpeaking(msg, new MySynthesizerListener());
    }

    class MySynthesizerListener implements SynthesizerListener {

        @Override
        public void onSpeakBegin() {
            //LogUtils.e("开始播放");
            long[] a = {1500,1000};
            VibratorUtil.Vibrate(context, a,false);   //震动1.5秒，停1秒，反复三次
        }

        @Override
        public void onSpeakPaused() {
            //LogUtils.e("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
            //LogUtils.e("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
            // 合成进度
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                //LogUtils.e("播放完成");
                playNum--;
                if (playNum > 0) {
                    speekText(playText);
                } else {
                    playText = "";
                    playNum = 3;
                }
            } else{
                LogUtils.e(error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话 id，当业务出错时将会话 id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话 id为null
            //if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //     String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //     Log.d(TAG, "session id =" + sid);
            //}
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
